﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using DAL.Models;
using DevExpress.Xpf.Editors.Settings;
using DevExpress.Xpf.Grid;
using DevExpress.Xpf.Editors;
using DevExpress.Xpf.Core;
using DevExpress.Xpf.Bars;
using WpfClient.Classes;
using DAL.BAL;
using System.Net.Mail;
using System.IO;

namespace WpfClient.Windows
{
    /// <summary>
    /// Interaction logic for VacancyEdit.xaml
    /// </summary>
    public partial class VacancyEdit : Window
    {
        private Vacancy vacancy = null;

        private List<CalendarEvent> calendarEvents = null;

        Dictionary<int, bool> selectedValues = new Dictionary<int, bool>();

        public VacancyEdit(Vacancy vacancy, bool isNew, bool canSave)
        {
            InitializeComponent();

            this.vacancy = vacancy;

            if (isNew)
            {
                this.Title = "Новая вакансия";

                this.vacancy.VacancyDate = DateTime.Now;
            }
            else
            {
                this.Title = "Вакансия";

                layoutGroup3.Header = string.Format("{0}.{1}",vacancy.Employer.EmployerName, vacancy.Position.PositionName);
            }

            bOk.SetVisible(canSave);

            calendarEvents = new List<CalendarEvent>();
                       
            #region init datasources

            ((ComboBoxEditSettings)gridCommodityGroups.Columns["CommodityGroup"].EditSettings).ItemsSource = Business.GetCommodityGroups().ToList();

            ((ComboBoxEditSettings)gridCandidateHistory.Columns["Candidate"].EditSettings).ItemsSource = (Business.GetRealCandidatesLookup().ToList());

            ((ComboBoxEditSettings)gridCandidateHistory.Columns["InterviewResult"].EditSettings).ItemsSource = LoadedData.InterviewResults;

            ((ComboBoxEditSettings)gridVacancyTerritory.Columns["Territory"].EditSettings).ItemsSource = Business.GetTerritories().ToList();

            cbAge_max.ItemsSource = LoadedData.Ages;

            cbAge_min.ItemsSource = LoadedData.Ages;
            
            cbStatus.ItemsSource = LoadedData.Vacancy_Types; 
            
            cbEmployer.ItemsSource = Business.GetEmployers().ToList();

            cbPosition.ItemsSource = Business.GetPositions().ToList();

            cbSalaryRange.ItemsSource = LoadedData.SalaryRanges;

            cbExpirience_priority.ItemsSource = LoadedData.CompareImportants;

            cbAge_priority.ItemsSource = LoadedData.CompareImportants;

            cbCar_priority.ItemsSource = LoadedData.CompareImportants;

            cbSexName_priority.ItemsSource = LoadedData.CompareImportants;

            cbPosition_priority.ItemsSource = LoadedData.CompareImportants;

            cbCar.ItemsSource = LoadedData.HasCars;
            
            cbSex.ItemsSource = Business.GetSexVariants(true).ToList();
            
            this.DataContext = this.vacancy;

 
            #endregion

            cbEmployer.EditValueChanged += cbEmployer_EditValueChanged;

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if ((vacancy.Employer != null) && (vacancy.Position != null))
            {
                foreach (CalendarEvent item in calendarEvents)
                {
                    Business.ChangeEventTime(Business.currentUser, item.EventDate, calendarEvents);

                    Business.dosvidEntities.CalendarEvents.AddObject(item);
                }
                
                Candidat_VacancyHistory cvh = (Candidat_VacancyHistory)gridCandidateHistory.GetFocusedRow();

                if (cvh != null)
                    if (cvh.Vacancy == null)
                    {
                        cvh.Vacancy = vacancy;

                        cvh.SendResumeDate = DateTime.Now.Date;
                    }

                this.DialogResult = true;

                this.Close();
            }
            else
                MessageBox.Show(WpfClient.Properties.Resources.ThereAreMandatoryFields, WpfClient.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Warning);
        }
 
        private void cbEmployer_EditValueChanged(object sender, EditValueChangedEventArgs e)
        {            
            if (vacancy.Employer != null)
            {
                var employees = Business.GetEmployees(vacancy.Employer).ToList();

                cbEmployeeWhoApproveCandidates.SelectedIndex = -1;

                cbEmployeeWhoFindCandidates.SelectedIndex = -1;

                cbEmployeeWhoApproveCandidates.ItemsSource = employees;

                cbEmployeeWhoFindCandidates.ItemsSource = employees;
            }

        }

        private void deDate_Validate(object sender, ValidationEventArgs e)
        {
            if (e.Value == null || e.Value.ToString() == string.Empty)
            {
                e.IsValid = false;

                e.ErrorContent = WpfClient.Properties.Resources.Field_Cant_Be_Empty;
            }
        }

        private void deleteRowItemCG_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (MessageBox.Show(WpfClient.Properties.Resources.AreYouSureYouWantDelete,
                    WpfClient.Properties.Resources.Warning, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {

                gridCommodityGroups.View.CommitEditing();

                DAL.Models.Vacancy_CommodityGroups ec = (DAL.Models.Vacancy_CommodityGroups)gridCommodityGroups.GetRow(gridCommodityGroups.View.FocusedRowHandle);

                (gridCommodityGroups.View as GridViewBase).DeleteRow(gridCommodityGroups.View.FocusedRowHandle);

                Business.DeleteObject(ec);
            }
        }

        private void deleteRowItemCH_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (MessageBox.Show(WpfClient.Properties.Resources.AreYouSureYouWantDelete,
                  WpfClient.Properties.Resources.Warning, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {

                gridCandidateHistory.View.CommitEditing();

                DAL.Models.Candidat_VacancyHistory ec = (DAL.Models.Candidat_VacancyHistory)gridCandidateHistory.GetRow(gridCandidateHistory.View.FocusedRowHandle);

                (gridCandidateHistory.View as GridViewBase).DeleteRow(gridCandidateHistory.View.FocusedRowHandle);

                Business.DeleteObject(ec);
            }
        }

        private void cbEmployeeWhoFindCandidates_EditValueChanged(object sender, EditValueChangedEventArgs e)
        {
            Candidate candidate = (Candidate)e.NewValue;

            if (candidate != null)
            {
                string _phones = string.Empty;

                foreach (Candidat_Phones cp in candidate.Candidat_Phones)
                {
                    _phones += string.Format("{0};", cp.Phone);
                }

                if (sender == cbEmployeeWhoFindCandidates)
                    tePhones1.Text = _phones;
                else
                    tePhones2.Text = _phones;

            }
        }

        private void gridCommodityGroups_ValidateRow(object sender, GridRowValidationEventArgs e)
        {
            if (((DAL.Models.Vacancy_CommodityGroups)e.Row).CommodityGroup == null)
            {
                e.ErrorContent = WpfClient.Properties.Resources.Field_Cant_Be_Empty + " (" +
                                 gridCommodityGroups.Columns["CommodityGroup"].Header + ")";
                e.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning;
                e.IsValid = false;

            }
            else
                e.IsValid = true;
        }

        private void TableView_InvalidRowException(object sender, InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = ExceptionMode.NoAction;
        }

        private void gridCandidateHistory_ValidateRow(object sender, GridRowValidationEventArgs e)
        {
            if (((DAL.Models.Candidat_VacancyHistory)e.Row).Candidate == null)
            {
                e.ErrorContent = WpfClient.Properties.Resources.Field_Cant_Be_Empty + " (" +
                                 gridCandidateHistory.Columns["Candidate"].Header + ")";
                e.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning;
                e.IsValid = false;

            }
            else
                if (((DAL.Models.Candidat_VacancyHistory)e.Row).SendResumeDate == null)
                {
                    e.ErrorContent = WpfClient.Properties.Resources.Field_Cant_Be_Empty + " (" +
                                     gridCandidateHistory.Columns["SendResumeDate"].Header + ")";
                    e.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning;
                    e.IsValid = false;

                }
                else
                    e.IsValid = true;
        }
 
        private void gridCandidateHistory_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            OpenCandidateInfo();
        }

        private void OpenCandidateInfo()
        {
            Candidat_VacancyHistory hist = (Candidat_VacancyHistory)gridCandidateHistory.GetFocusedRow();

            if (hist != null)
            {
                Candidate candidate = (from n in Business.GetCandidates()
                                       where n.Id == hist.Candidate.Id
                                       select n).FirstOrDefault();

                if (candidate != null)
                    if (new CandidateEdit(candidate, false, true).ShowDialog() == true)
                    {
                        Business.Save();

                        gridCandidateHistory.RefreshData();
                    }
            }
        }

        private void candidateInfo_ItemClick(object sender, ItemClickEventArgs e)
        {
            OpenCandidateInfo();
        }

        private void CreateCalendarEvents(Vacancy _vacancy, Candidate candidate, bool AutoSave)
        {
            CalendarEvent calendarEvent = new CalendarEvent();

            calendarEvent.EventDate = DateTime.Today.AddDays(1);

            calendarEvent.User = Business.currentUser;

            calendarEvent.User1 = Business.currentUser;

            calendarEvent.IsAutoCreated = true;

            calendarEvent.Vacancy = this.vacancy;

            calendarEvent.CreatedDate = DateTime.Today;

            calendarEvent.CalendarEventStatus = (from n in Business.GetCalendarEventStatuses()
                                                 where n.Id == 1
                                                 select n).FirstOrDefault();

            calendarEvent.CalendarEventType = (from n in Business.GetCalendarEventTypes()
                                               where n.Id == 1
                                               select n).FirstOrDefault();

            calendarEvent.EventText = Business.CreateCallEventText(_vacancy, candidate);

            if (AutoSave)
            {
                Business.dosvidEntities.CalendarEvents.AddObject(calendarEvent);
            }
            else
            {
                calendarEvents.Add(calendarEvent);
            }
        }

        private void TableView_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            DAL.Models.Candidat_VacancyHistory item = (DAL.Models.Candidat_VacancyHistory)gridCandidateHistory.GetRow(gridCandidateHistory.View.FocusedRowHandle);

            if (item != null)
            {
                if (e.Column == columnInterviewDate)
                {
                    #region Create calendar event

                    CreateCalendarEvents(vacancy, item.Candidate, false);

                    #endregion
                }
            }
        }

        private void gridCandidateHistory_CustomUnboundColumnData(object sender, GridColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "Selected")
            {
                int key = (int)e.GetListSourceFieldValue("Id");
                if (e.IsGetData)
                {
                    e.Value = GetIsSelected(key);
                }
                if (e.IsSetData)
                {
                    SetIsSelected(key, (bool)e.Value);
                }
            }
            else
                if (e.Column == columnPhone)
                {
                    Candidate candidate = (Candidate)e.GetListSourceFieldValue("Candidate");

                    if (candidate != null)
                    {
                        if (e.IsGetData)
                        {
                            string _phones = string.Empty;

                            foreach (Candidat_Phones cp in candidate.Candidat_Phones)
                            {
                                _phones += string.Format("{0};", cp.Phone);
                            }

                            e.Value = _phones;
                        }
                    }
                }
        }

        private void deleteRowItemCandidate_RangeTerritory_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (MessageBox.Show(WpfClient.Properties.Resources.AreYouSureYouWantDelete,
             WpfClient.Properties.Resources.Warning, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {
                gridVacancyTerritory.View.CommitEditing();

                DAL.Models.Vacancy_Territories ec = (DAL.Models.Vacancy_Territories)gridVacancyTerritory.GetRow(gridVacancyTerritory.View.FocusedRowHandle);

                (gridVacancyTerritory.View as GridViewBase).DeleteRow(gridVacancyTerritory.View.FocusedRowHandle);

                Business.DeleteObject(ec);
            }
        }

        private bool GetIsSelected(int key)
        {
            bool isSelected;
            if (selectedValues.TryGetValue(key, out isSelected))
                return isSelected;
            return false;
        }

        private void SetIsSelected(int key, bool value)
        {
            if (value)
                selectedValues[key] = value;
            else
                selectedValues.Remove(key);
        }

        private void SendPhones_Click(object sender, RoutedEventArgs e)
        {
            foreach (int key in selectedValues.Keys)
            {
                Candidat_VacancyHistory candidateHist = (from n in Business.dosvidEntities.Candidat_VacancyHistory
                                                         where n.Id == key
                                                         select n).FirstOrDefault();

                if (candidateHist != null)
                {
                    #region create Send Mail

                    SendEmail sendEmail = new SendEmail();

                    sendEmail.SMTPAdress = Business.currentUser.EMail_SMTP_Server;

                    sendEmail.Password = Business.currentUser.EMail_Password;

                    sendEmail.UserName = Business.currentUser.Emil_UserName;

                    #endregion

                    MailMessage message = null;

                    try
                    {
                        message = EmailMessage.CreateMessagePhones(vacancy, candidateHist.Candidate);

                        if (message != null)
                        {
                            sendEmail.Message = message;

                            sendEmail.Send();

                            sendEmail.Dispose();

                            #region Save result to DB

                            candidateHist.InterviewDate = DateTime.Today;

                            CreateCalendarEvents(vacancy, candidateHist.Candidate, true);

                            Business.Save();

                            #endregion

                            MessageBox.Show(WpfClient.Properties.Resources.MessageWasSent, WpfClient.Properties.Resources.Warning, MessageBoxButton.OK, MessageBoxImage.Information);

                        }
                    }
                    catch (Exception e1)
                    {
                        MessageBox.Show(e1.Message, WpfClient.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    finally
                    {
                        if (message != null)
                        {
                            string fileForDelete = string.Empty;

                            if (message.Attachments.FirstOrDefault() != null)
                                fileForDelete = message.Attachments.FirstOrDefault().Name;

                            message.Dispose();

                            EmailMessage.DeleteFile(fileForDelete);
                        }
                    }
                }
            }
                      
        }

        private void btOpen_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (Environment.GetEnvironmentVariable("Temp") != string.Empty)
                {
                    if (vacancy.Vacancy_Resume !=null)
                    {
                        string fileName = string.Format("{0}{1}", Environment.GetEnvironmentVariable("Temp"),vacancy.ResumeName);

                        System.IO.File.WriteAllBytes(fileName,vacancy.Vacancy_Resume.FirstOrDefault().Resume );

                        System.Diagnostics.Process process = new System.Diagnostics.Process();

                        process.StartInfo.FileName = fileName;

                        process.Start();

                    }
                }
                else
                    MessageBox.Show(WpfClient.Properties.Resources.TherIsNotTempFolder, WpfClient.Properties.Resources.Warning, MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message, WpfClient.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void beResume_DefaultButtonClick(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = string.Empty;
            dlg.DefaultExt = ".doc;.docx";
            dlg.Filter = "Word documents (.doc,.docx)|*.doc;*.docx";

            Nullable<bool> result = dlg.ShowDialog();

            if (result == true)
            {
                try
                {
                    if (vacancy.Vacancy_Resume.Count==0)
                    {
                        Vacancy_Resume vacancyResume = new Vacancy_Resume(); 
                        vacancyResume.VacancyId = vacancy.Id;
                        vacancyResume.Resume = File.ReadAllBytes(dlg.FileName);

                        vacancy.Vacancy_Resume.Add(vacancyResume);
                    }
                    else
                    {
                        vacancy.Vacancy_Resume.FirstOrDefault().Resume = File.ReadAllBytes(dlg.FileName); 
                    }
                    vacancy.ResumeName = System.IO.Path.GetFileName(dlg.FileName);
                }
                catch (Exception e1)
                {
                    MessageBox.Show(e1.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }

            }
        }

        private void btLoad_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                  if(vacancy.Vacancy_Resume !=null)
                {
                    Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                    dlg.FileName = vacancy.ResumeName;
                    dlg.DefaultExt = System.IO.Path.GetExtension(vacancy.ResumeName );
                    dlg.Filter = "Word documents (.doc,.docx)|*.doc;*.docx";

                    // Show save file dialog box
                    Nullable<bool> result = dlg.ShowDialog();


                    // Process save file dialog box results
                    if (result == true)
                    {
                         System.IO.File.WriteAllBytes(dlg.FileName, vacancy.Vacancy_Resume.FirstOrDefault().Resume);
                    }
                }
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message, WpfClient.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

    }
}

 